package com.micro.ai.commons.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 请求工具类
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
public final class RequestUtils {

    private RequestUtils() {
        throw new UnsupportedOperationException("工具类不允许实例化");
    }

    /**
     * 获取当前请求
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }

    /**
     * 获取请求ID
     */
    public static String getRequestId() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getHeader("X-Request-Id");
        }
        return null;
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            String userIdStr = request.getHeader("X-User-Id");
            if (userIdStr != null && !userIdStr.isEmpty()) {
                try {
                    return Long.parseLong(userIdStr);
                } catch (NumberFormatException e) {
                    log.warn("用户ID格式错误: {}", userIdStr);
                }
            }
        }
        return null;
    }

    /**
     * 获取租户ID
     */
    public static String getTenantId() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getHeader("X-Tenant-Id");
        }
        return null;
    }

    /**
     * 获取客户端IP地址（从当前请求上下文）
     */
    public static String getClientIp() {
        HttpServletRequest request = getCurrentRequest();
        if (request == null) {
            return null;
        }
        return getClientIp(request);
    }

    /**
     * 获取客户端真实IP地址
     * 
     * @param request HTTP请求
     * @return IP地址
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = null;
        
        // 1. 检查X-Forwarded-For头
        ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            // 多级代理的情况，第一个IP为客户端真实IP
            if (ip.contains(",")) {
                ip = ip.split(",")[0].trim();
            }
            return ip;
        }
        
        // 2. 检查X-Real-IP头
        ip = request.getHeader("X-Real-IP");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        
        // 3. 检查Proxy-Client-IP头
        ip = request.getHeader("Proxy-Client-IP");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        
        // 4. 检查WL-Proxy-Client-IP头
        ip = request.getHeader("WL-Proxy-Client-IP");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        
        // 5. 检查HTTP_CLIENT_IP头
        ip = request.getHeader("HTTP_CLIENT_IP");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        
        // 6. 检查HTTP_X_FORWARDED_FOR头
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        
        // 7. 使用request.getRemoteAddr()
        ip = request.getRemoteAddr();
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        
        return "unknown";
    }

    /**
     * 获取用户代理（从当前请求上下文）
     */
    public static String getUserAgent() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getHeader("User-Agent");
        }
        return null;
    }

    /**
     * 获取User-Agent
     * 
     * @param request HTTP请求
     * @return User-Agent
     */
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }

    /**
     * 获取设备类型
     * 
     * @param userAgent User-Agent字符串
     * @return 设备类型
     */
    public static String getDeviceType(String userAgent) {
        if (userAgent == null) {
            return "unknown";
        }
        
        String ua = userAgent.toLowerCase();
        
        if (ua.contains("mobile") || ua.contains("android") || ua.contains("iphone")) {
            return "mobile";
        } else if (ua.contains("tablet") || ua.contains("ipad")) {
            return "tablet";
        } else {
            return "desktop";
        }
    }

    /**
     * 获取浏览器类型
     * 
     * @param userAgent User-Agent字符串
     * @return 浏览器类型
     */
    public static String getBrowserType(String userAgent) {
        if (userAgent == null) {
            return "unknown";
        }
        
        String ua = userAgent.toLowerCase();
        
        if (ua.contains("chrome")) {
            return "chrome";
        } else if (ua.contains("firefox")) {
            return "firefox";
        } else if (ua.contains("safari")) {
            return "safari";
        } else if (ua.contains("edge")) {
            return "edge";
        } else if (ua.contains("opera")) {
            return "opera";
        } else {
            return "unknown";
        }
    }

    /**
     * 获取请求URL
     */
    public static String getRequestUrl() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getRequestURL().toString();
        }
        return null;
    }

    /**
     * 获取请求URI
     */
    public static String getRequestUri() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getRequestURI();
        }
        return null;
    }

    /**
     * 获取请求方法
     */
    public static String getRequestMethod() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getMethod();
        }
        return null;
    }

    /**
     * 获取请求头
     */
    public static String getHeader(String name) {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getHeader(name);
        }
        return null;
    }

    /**
     * 获取请求参数
     */
    public static String getParameter(String name) {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            return request.getParameter(name);
        }
        return null;
    }

    /**
     * 判断是否为Ajax请求
     */
    public static boolean isAjaxRequest() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            String requestedWith = request.getHeader("X-Requested-With");
            return "XMLHttpRequest".equals(requestedWith);
        }
        return false;
    }

    /**
     * 判断是否为移动端请求
     */
    public static boolean isMobileRequest() {
        String userAgent = getUserAgent();
        if (userAgent == null) {
            return false;
        }
        
        String mobileRegex = "Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini";
        return userAgent.matches(".*(" + mobileRegex + ").*");
    }

    /**
     * 获取本机IP地址
     */
    public static String getLocalIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("获取本机IP失败", e);
            return "127.0.0.1";
        }
    }

    /**
     * 获取本机主机名
     */
    public static String getLocalHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            log.error("获取本机主机名失败", e);
            return "localhost";
        }
    }
}
